#!/bin/bash

# cjgit - New Command
# Create a new branch from upstream/dev in all projects

# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/cjgit-common.sh"

# New command implementation
new_command() {
    local branch_name="$1"
    
    # Validate branch name
    if [[ -z "$branch_name" ]]; then
        print_error "Branch name is required"
        echo
        help_command
        exit 1
    fi
    
    # Check if branch name contains spaces
    if [[ "$branch_name" =~ [[:space:]] ]]; then
        print_error "Branch name cannot contain spaces: '$branch_name'"
        exit 1
    fi
    
    print_info "Starting new branch creation: $branch_name"
    print_info "Stage 1: Checking for local changes in all projects..."
    echo
    
    # Stage 1: Check for local changes
    for project in "${PROJECTS[@]}"; do
        print_info "Checking project: $project"
        
        # Check if project directory exists
        if [[ ! -d "$project" ]]; then
            print_error "Project directory '$project' not found!"
            exit 1
        fi
        
        # Check if it's a git repository
        if [[ ! -d "$project/.git" ]]; then
            print_error "'$project' is not a git repository!"
            exit 1
        fi
        
        # Check for local changes
        if has_local_changes "$project"; then
            print_error "Local changes detected in '$project'! Cannot create new branch."
            print_error "Please commit or stash your changes first."
            exit 1
        else
            print_success "No local changes in '$project'"
        fi
    done
    
    print_success "Stage 1 completed: No local changes found in any project"
    echo
    print_info "Stage 2: Creating new branch '$branch_name' from upstream/dev..."
    echo
    
    # Stage 2: Create new branches
    for project in "${PROJECTS[@]}"; do
        print_info "Processing project: $project"
        
        # Find the upstream remote
        upstream_remote=$(find_cangjie_remote "$project")
        if [[ -z "$upstream_remote" ]]; then
            print_error "No Cangjie remote found in '$project'!"
            exit 1
        fi
        
        print_info "Found upstream remote: $upstream_remote"
        
        # Fetch from upstream
        print_info "Fetching from $upstream_remote..."
        if ! git -C "$project" fetch "$upstream_remote"; then
            print_error "Failed to fetch from $upstream_remote in '$project'"
            exit 1
        fi
        
        # Check if upstream/dev exists
        if ! git -C "$project" show-ref --verify --quiet "refs/remotes/$upstream_remote/dev"; then
            print_error "Remote branch '$upstream_remote/dev' does not exist in '$project'!"
            exit 1
        fi
        
        # Create new branch from upstream/dev
        if ! git -C "$project" checkout -b "$branch_name" "$upstream_remote/dev"; then
            print_error "Failed to create branch '$branch_name' in '$project'"
            exit 1
        fi
        
        # Set up tracking for upstream remote (pull)
        if ! git -C "$project" branch --set-upstream-to="$upstream_remote/dev" "$branch_name"; then
            print_warning "Failed to set upstream tracking in '$project'"
        fi
        
        # Set up myfork as push remote if it exists
        if has_myfork_remote "$project"; then
            # Set push remote to myfork
            if git -C "$project" config "branch.$branch_name.pushRemote" "myfork"; then
                # Push the branch to myfork
                if git -C "$project" push myfork "$branch_name" 2>/dev/null; then
                    print_success "$project: Created branch '$branch_name' with upstream tracking and pushed to myfork"
                else
                    print_warning "$project: Created branch '$branch_name' but failed to push to myfork"
                fi
            else
                print_warning "$project: Created branch '$branch_name' but failed to set push remote"
            fi
        else
            print_success "$project: Created branch '$branch_name' with upstream tracking (no myfork remote)"
        fi
        
        echo
    done
    
    print_success "New branch '$branch_name' created successfully in all projects"
}

# Help function for new command
help_command() {
    echo "Usage: cjgit new <branch_name>"
    echo
    echo "Create a new branch from upstream/dev in all projects"
    echo
    echo "Arguments:"
    echo "  branch_name    Name of the new branch to create"
    echo
    echo "Examples:"
    echo "  cjgit new feature-branch       # Create new branch from upstream/dev in all projects"
}

# Main execution
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    help_command
    exit 0
fi

if [[ -z "$1" ]]; then
    print_error "Branch name is required"
    echo
    help_command
    exit 1
fi

new_command "$1"